import React, { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { intl, nanoid10 } from "@/utils";
import { Button, Popup } from 'devextreme-react';
import { CpasIcon, DevPopup, LayoutB } from '~/public/cpas-ui';
import DataGrid, { Column, Editing, Item, Lookup, Paging, Selection, Toolbar } from 'devextreme-react/data-grid';
import { getCpasIcon } from '@/utils/icon';

import { getPersonnelList, templateCopyXlsxFile, templateReadXlsxFile, updateSaveDataBatch, updateSaveOneData } from './service'
import notify from 'devextreme/ui/notify';
import { useModel } from "umi";
import './index.less';
import { Workbook } from 'exceljs';
import { saveAs } from "file-saver";
import { exportDataGrid } from 'devextreme/excel_exporter';

const PersonnelMaintenancePupop = React.forwardRef((props: any, ref: any) => {

    const { initialState } = useModel('@@initialState');
    const { relaodTable } = props;
    const { dbname } = initialState?.curPart as any;
    const [visible, setVisible] = useState<boolean>(false);
    const popupRef = useRef<any>(null);
    const dataGridRef = useRef<any>(null);
    const deltePupopRef = useRef<any>(null);
    const modalExtensions = ["doc", "docx", "xls", "xlsx", "jpg", "gif", "bmp", "png", "txt", "pdf", "rar", "rar4", "zip", "mp3", "mp4",
        'xlsm', 'xltm', 'xlam', 'xlsb', 'csv'];

    const [employeesData, setEmployeesData] = useState<any[]>([]);
    // const [eventsSaveData, setEventsSaveData] = useState<any[]>([]);

    const eventsSaveData = useRef<any[]>([]);

    const onCancel = () => {
        setVisible(false);
        setEmployeesData([]);
        eventsSaveData.current = [];
    };

    const getDataList = async () => {

        const res = await getPersonnelList({ dbname });
        if (res.success) {
            setEmployeesData(res.data);
            eventsSaveData.current = res.data;
        } else {
            setEmployeesData([]);
            eventsSaveData.current = [];
        }
    };

    const onOk = () => {

        dataGridRef.current.instance.saveEditData().then(async () => {
            const interAndAdd = eventsSaveData.current.filter((item) => item.rowState);
            const interKong = eventsSaveData.current.filter((item) => !item.name);
            if (interKong.length) return notify('姓名不能为空！', 'warning', 2000);
            // 提取所有的 name 值
            const namesArr = eventsSaveData.current.map(item => item.name);
            // 使用 Set 来检测重复
            const uniqueNames = new Set(namesArr);
            if (namesArr.length !== uniqueNames.size) return notify('姓名存在相同，禁止提交！', 'warning', 2000);

            // 找出具体的重复项
            // const duplicates = names.filter((item, index) => names.indexOf(item) !== index);
            // const uniqueDuplicates = Array.from(new Set(duplicates));
            // console.log("重复的 name 值:", uniqueDuplicates);
            const tempA: any = [];
            for (let index = 0; index < interAndAdd.length; index++) {
                const element = interAndAdd[index];
                let apiName = '';
                if (element.rowState === "delete") {
                    apiName = 'accountingEntryTest.accountant.deleteOneData';
                } else {
                    apiName = 'accountingEntryTest.accountant.saveOneData';
                }
                const res: any = await updateSaveOneData(apiName, {
                    dbname,
                    ...element
                });

                if (res.success) {
                    tempA.push(Promise.resolve('ok'));
                } else {
                    tempA.push(Promise.resolve(`${element.name}添加失败`));
                }
            }
            Promise.allSettled(tempA).then(results => {
                const falseData = results.filter((item1: any) => item1.value !== 'ok').map((item: any) => item.value);
                if (falseData.length) {
                    notify(`增加人员，失败原因为【${falseData.join(';')};】`, 'error', 4000);
                } else {
                    notify("增加人员成功！", 'success', 2000);
                    relaodTable();
                    onCancel();
                }
            }).catch(error => {
                // 处理错误
                console.error("An error occurred:", error);
            });
        });

    };


    // 自定义方法
    useImperativeHandle(ref, () => ({
        showMaintenancePupop: () => {
            getDataList();
            setVisible(true);
        },
    }));



    const SavedData = (e: any) => {
        if (e.changes.length) {
            const { data } = e.changes[0];
            const tempID = data.guid;
            let changeData = { ...data, name: data.name.trim() }
            const filterData = eventsSaveData.current.filter(item => item.guid === tempID);
            setEmployeesData((oldData: any) => {
                let newData = [...oldData];
                newData.forEach(item => {
                    if (item.guid === tempID) {
                        item = { ...item, ...changeData };
                    }
                    return { ...item, name: item.name.trim() };
                });
                return newData;
            });
            const changeSaveData = (oldData: any[]) => {
                let newData1 = [...oldData];
                if (filterData.length) {
                    newData1 = newData1.map(item => {
                        if (item.guid === tempID) {
                            const newItem = { ...changeData };
                            if (newItem.isAdd === 1 && !newItem.rowState) {
                                newItem.rowState = 'update';
                            };
                            return newItem;
                        }
                        return { ...item };
                    });
                    return newData1;
                } else {
                    newData1.push({ ...changeData, rowState: 'insert' });
                    return newData1;
                };
            };
            eventsSaveData.current = changeSaveData(eventsSaveData.current);
        }
    };


    const onExporting = async () => {
        // const workbook = new Workbook();
        // const worksheet: any = workbook.addWorksheet('会计人员清单');
        // const dataGridInstance = dataGridRef.current.instance;
        // const originalColumns = dataGridInstance.option('columns');
        // const columnsToExport = originalColumns.map((column: any) => {
        //     if (!column.dataField) {
        //         return { ...column, visible: false };
        //     }
        //     return column;
        // });
        // dataGridInstance.option('columns', columnsToExport);
        // exportDataGrid({
        //     component: dataGridInstance,
        //     worksheet,
        //     autoFilterEnabled: true,
        //     customizeCell({ excelCell, gridCell }: any) {
        //         const borderStyle = { style: "thin", color: { argb: "000000" } };
        //         excelCell.border = {
        //             bottom: borderStyle,
        //             left: borderStyle,
        //             right: borderStyle,
        //             top: borderStyle,
        //         };
        //     }
        // }).then(() => {


        //     workbook.xlsx.writeBuffer().then((buffer) => {
        //         saveAs(new Blob([buffer], { type: 'application/octet-stream' }), '会计人员清单导入模板.xlsx');
        //     });
        //     // Restore the original column configuration after export
        //     dataGridInstance.option('columns', originalColumns);
        // });


        let electronComponents: any;
        if (window.parent) {
            electronComponents = window.parent?.electronComponents as any;
        } else {
            electronComponents = window?.electronComponents as any;
        }
        const xlsx_result = await electronComponents.openDirectoryDialog();
        const checkFolderPath = xlsx_result.filePaths[0];
        if (!xlsx_result.canceled) {
            console.log(checkFolderPath, '@@@');
            const res = await templateCopyXlsxFile({ targetFile: checkFolderPath });
            if (res.success) {
                notify('导出模版成功', 'success', 2000);

            } else {
                notify('导出模版失败', 'error', 2000);
            }
        }
    };

    const onExportingTo = async () => {
        let electronComponents: any;
        if (window.parent) {
            electronComponents = window.parent?.electronComponents as any;
        } else {
            electronComponents = window?.electronComponents as any;
        }
        const xlsx_result = await electronComponents.openDialog({
            properties: ['openFile'],
            filters: [
                {
                    name: 'Office Files',
                    extensions: modalExtensions,
                }, { name: 'all', extensions: ["*"] }
            ],
        });
        const checkFolderPath = xlsx_result.filePaths[0];
        if (!xlsx_result.canceled) {
            console.log(checkFolderPath, '@@@');
            const res = await templateReadXlsxFile({ targetFile: checkFolderPath });
            if (res.success) {
                let { reData } = res.data;
                setEmployeesData((oldData: any) => {
                    let newData = [...oldData, ...reData];
                    return newData;
                });

                const changeSaveData_xlsx = (oldData: any[]) => {
                    let newData1 = [...oldData];
                    reData.forEach((item: any) => {
                        item.rowState = 'insert';
                    });
                    newData1 = [...newData1, ...reData];
                    return newData1;
                }

                eventsSaveData.current = changeSaveData_xlsx(eventsSaveData.current);

                notify('导入模版成功', 'success', 2000);
            }
        } else {
            notify('导入模版失败', 'error', 2000);
        }
    };


    function leftContainer() {
        return (
            <div style={{ marginRight: "15px", height: "100%" }} key={nanoid10()}>
                <DataGrid
                    className='devHeadersCenter PaperDevSortableGrid personnelMaintenanceDataGrid'
                    ref={dataGridRef}
                    dataSource={employeesData}
                    keyExpr="guid"
                    height="100%"
                    showBorders={true}
                    showRowLines={true}
                    showColumnLines={true}
                    rowAlternationEnabled={true}
                    allowHeaderFiltering={false}
                    allowSorting={false}
                    // headerFilter={{ visible: false }}
                    // filterPanel={{ visible: false }}
                    // filterRow={{ visible: false }}
                    onSaved={SavedData}
                    searchPanel={{
                        visible: true,
                        width: 180,
                        placeholder: '',
                    }}
                >
                    <Toolbar>
                        <Item location="after">
                            <Button
                                icon='iconfont icon-add-circle1'
                                text='新增'
                                className='refreshButton_Style'
                                onClick={async () => {
                                    // const dataGridInstance = dataGridRef.current.instance;
                                    // await dataGridInstance.addRow();
                                    // const newRowRowIndex = dataGridInstance.getDataSource().items().length;
                                    // let rowIndex = 0;
                                    // let textIndex = 0;
                                    // if (newRowRowIndex < 1) {
                                    //     rowIndex = newRowRowIndex;
                                    // }
                                    // textIndex = newRowRowIndex + 1;
                                    // const newRowData = {
                                    //     guid: nanoid10() + new Date().getTime(),
                                    //     code: `000${textIndex}`,
                                    //     name: '',
                                    //     job: '',
                                    // };
                                    // dataGridInstance.cellValue(rowIndex, 'code', newRowData.code);
                                    // dataGridInstance.cellValue(rowIndex, 'name', newRowData.name);
                                    // dataGridInstance.cellValue(rowIndex, 'job', newRowData.job);
                                    setEmployeesData((oldData: any) => {
                                        let newData = [...oldData];
                                        newData.push({
                                            guid: nanoid10() + new Date().getTime(),
                                            code: `000${newData.length + 1}`,
                                            name: '',
                                            job: '',
                                            rowState: 'insert'
                                        });
                                        return newData;
                                    });
                                }} />
                        </Item>
                        <Item location="after" name="searchPanel" />
                        <Item location="after">
                            <Button
                                icon='iconfont icon-refresh'
                                className='refreshButton_Style'
                                onClick={() => { }} />
                        </Item>
                    </Toolbar>
                    <Paging enabled={false} />
                    <Editing
                        mode="cell"
                        allowUpdating={true}
                        allowAdding={false}
                        allowDeleting={false} />
                    <Column
                        caption="编号"
                        dataField="code"
                        width={100}
                    />
                    <Column
                        caption="姓名"
                        dataField="name"
                        width={150}
                    />
                    <Column
                        caption="岗位"
                        dataField="job"
                    />
                    <Column
                        caption=""
                        // dataField="Position"
                        width={50}
                        allowEditing={false}
                        cellRender={(e) => {
                            const { data } = e;
                            return <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'red' }}
                                onClick={() => {
                                    deltePupopRef.current.show({
                                        title: "提示",
                                        okCallback: () => {
                                            setEmployeesData((oldData) => {
                                                let newData = [...oldData];
                                                newData = newData.filter(item => item.guid !== data.guid);
                                                return newData;
                                            });

                                            const changeSaveDataDel = (oldData: any) => {
                                                let newData1 = [...oldData];
                                                newData1.forEach((item, index) => {
                                                    if (item.guid === data.guid) {
                                                        if (item.isAdd === 1) {
                                                            item.rowState = 'delete';
                                                        } else {
                                                            newData1.splice(index, 1); // 从数组中移除当前项
                                                        }
                                                    }
                                                });
                                                return newData1;
                                            }
                                            eventsSaveData.current = changeSaveDataDel(eventsSaveData.current);
                                        }
                                    });
                                }}>
                                <CpasIcon type={'icon-close1'} fontSize={16} />
                            </div>;
                        }}
                    />
                </DataGrid>

            </div>
        );
    }


    return (
        <>
            <Popup
                ref={popupRef}
                visible={visible}
                title='会计人员清单维护'
                width={700}
                height={'70vh'}
                // dragOutsideBoundary={true}
                // resizeEnabled={true}
                onHiding={() => { onCancel() }}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'before',
                        options: {
                            text: '导出Excel模板',
                            width: 150,
                            icon: 'iconfont icon-download1',
                            onClick: () => {

                                onExporting();

                            }
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'before',
                        options: {
                            text: '导入',
                            icon: 'iconfont icon-congwaibudaoru',
                            onClick: async () => {

                                onExportingTo();

                            }
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },

                ]}
                contentRender={() => (
                    <div style={{ height: '100%', width: '100%', overflow: 'hidden' }} >
                        {leftContainer()}
                    </div>
                )}
            />

            <DevPopup.Default ref={deltePupopRef} width={80} height={220}  >
                {() => {
                    return <span>确定要执行此删除操作吗？</span>
                }}
            </DevPopup.Default>
        </>
    );
});

export default PersonnelMaintenancePupop;
